<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/6/1
 * Time: 14:07
 */

namespace App\Repository;


use App\Category;
use App\Content;
use App\Exceptions\BusinessException;
use App\Exceptions\ValidatorException;
use Illuminate\Support\Facades\Validator;

class ContentRepository
{

    /**
     * 正文列表
     *
     * @param int $offset
     * @param int $range
     * @param array $params
     * @return array
     */
    public function index(int $offset = 0, int $range = 15, array $params)
    {
        $query = Content::query()
            ->when(!empty($params['title']), function ($query) use ($params) {
                $query->where('title', 'like', "%{$params['title']}%");
            })->when(!empty($params['c_id']), function ($query) use ($params) {
                $cid = Category::query()->where('type', $params['c_id'])->select('id')->get();
                $query->whereIn('c_id', $cid);
            })->orderBy('sort', 'DESC');

        return [
            'offset' => $offset,
            'range' => $range,
            'total' => $query->count(),
            'params' => $params,
            'items' => $query->offset($offset)->limit($range)->with(['category:id,title'])->get()
        ];
    }
    /**
     * 增加文章
     *
     * @param array $data
     * @return mixed
     * @throws ValidatorException
     */
    public function create(array $data)
    {
        $this->validator($data);
        try {
            $content = Content::create($data);
        } catch (\Exception $e) {
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了', 500);
        }
        return $content;
    }

    /**
     * 修改分类
     *
     * @param array $data
     * @param Content $content
     * @return bool
     */
    public function update(array $data, Content $content)
    {
        try {
            return $content->update($data);
        } catch (\Exception $e) {
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了', 500);
        }
    }

    /**
     * 表单验证
     *
     * @param array $data
     * @return bool
     * @throws ValidatorException
     */
    private function validator(array $data)
    {
        $validator = Validator::make($data, [
            'title' => 'required',
            'c_id' => 'required',
        ], [
            'required' => ':attribute 不能为空',
        ], [
            'title' => '标题',
            'c_id' => '分类',
        ]);

        if ($validator->fails()) {
            throw new ValidatorException($validator);
        }
        return true;
    }
}